<template>
    <!-- 头部区域 -->
    <van-nav-bar title="用户注册" left-text="返回" left-arrow @click-left="$router.go(-1)" />
    <!-- 注册区域 -->
    <van-form @submit="onSubmit" class="register-input">
        <van-cell-group>
            <van-field v-model="username" name="loginname" label="手机号" placeholder="填写手机号"
                :rules="[{ required: true, message: '请填写手机号' }]" />
            <van-field v-model="verCode" center clearable name="varcode" label="短信验证码" placeholder="请输入短信验证码"
                :rules="[{ required: true, message: '请输入验证码' }]">
                <template #button>
                    <van-button size="small" type="danger" @click="getVerCode">发送验证码</van-button>
                </template>
            </van-field>
            <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]" />
        </van-cell-group>
        <div style="margin: 16px;">
            <van-button round block type="danger" native-type="submit">
                注册
            </van-button>
        </div>
    </van-form>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import type { Ref } from 'vue';
import { useRouter } from 'vue-router'
import { VerificatPhone, AdminReg, SendSms } from '@/api/api';
import { showToast } from 'vant';


interface IRequstObj {
    code: string,
    message: string,
    data: string,
}

const username: Ref<string> = ref('');
const verCode: Ref<string> = ref('');
const password: Ref<string> = ref('');
const router = useRouter();
//获取验证码
const getVerCode = async () => {
    if (!username.value) return;
    const isRegister = (await VerificatPhone({ tel: username.value })) as unknown as IRequstObj;
    if (isRegister.code !== "200") {
        const res = (await SendSms({ tel: username.value })) as unknown as IRequstObj;
        if (res.code === "200") {
            verCode.value = res.data;
            showToast({
                message: res.message,
                position: 'bottom'
            })
        }
    }

}
const onSubmit = async () => {
    const res = await AdminReg({
        tel: username.value,
        password: password.value
    })
    if (res.data.code === '200') {
        showToast({
            message: res.data.message,
            position: 'bottom'
        })
        router.push({ path: '/login', query: { id: username.value } })
    }

}
</script>

<style scoped lang="scss">
.register-input {
    margin-top: 30px;
}
</style>